package com.suxin.datahub.util;

import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @Classname JdbcUtils
 * @Description [ JdbcUtils ]
 * @Author Tang
 * @Date 2020/11/10 15:45
 * @Created by ASUS
 */
@Slf4j
public class JdbcUtils {

    public static ResultSet executeQuery(String sql,Connection connection,Object[] params) {
        try {
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            if (params != null) {
                setParameter(preparedStatement, params);
            }
            return preparedStatement.executeQuery();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

    public static int executeUpdate(String sql,Connection connection,Object[] params) {
        return executeDml(sql, connection, params);
    }

    public static int executeDelete(String sql,Connection connection,Object[] params) {
        return executeDml(sql, connection, params);
    }

    public static int executeInsert(String sql,Connection connection,Object[] params) {
        return executeDml(sql, connection, params);
    }

    private static int executeDml(String sql,Connection connection,Object[] params) {
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = connection.prepareStatement(sql);
            if (params != null) {
                setParameter(preparedStatement, params);
            }
            return preparedStatement.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return 0;
    }

    private static void setParameter(PreparedStatement statement, Object[] arg) {
        for (int i = 0; i < arg.length; i++) {
            try {
                statement.setObject(i + 1, arg[i]);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

}